<template>
  <div class="registration-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
 
      <div class="stats flex space-x-4 mt-4">
        <div class="stat-card bg-primary-100 rounded-lg shadow p-4 flex-1 animate-pulse">
          <div class="text-sm text-primary-600">今日报名</div>
          <div class="text-2xl font-bold text-primary-900 mt-1">{{ todayRegistrations }}</div>
        </div>
        <div class="stat-card bg-secondary-100 rounded-lg shadow p-4 flex-1 animate-pulse">
          <div class="text-sm text-secondary-600">热门团（10人以上）</div>
          <div class="text-2xl font-bold text-secondary-900 mt-1">{{ popularToursCount }}</div>
        </div>
        <div class="stat-card bg-info-100 rounded-lg shadow p-4 flex-1 animate-pulse">
          <div class="text-sm text-info-600">总报名数</div>
          <div class="text-2xl font-bold text-info-900 mt-1">{{ total }}</div>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area bg-white rounded-lg shadow mt-6 p-4">
      <el-form :inline="true" :model="searchForm" class="flex flex-wrap gap-4">
        <el-form-item label="团名称">
          <el-input v-model="searchForm.groupName" placeholder="请输入团名称" clearable class="input-bordered"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable class="input-bordered"></el-input>
        </el-form-item>
        <el-form-item label="报名日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="input-bordered"
          ></el-date-picker>
        </el-form-item>
        <el-form-item class="flex items-end ml-auto">
          <el-button type="primary" @click="handleSearch" class="btn-primary">
            <i class="el-icon-search"></i> 查询
          </el-button>
          <el-button type="default" @click="handleReset" class="btn-secondary ml-2">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area bg-white rounded-lg shadow mt-6 overflow-hidden">
      <el-table
        :data="formattedTableData"
        border
        stripe
        size="small"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        :row-key="row => row.registrationId"
        class="el-table--fit"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="registrationNumber" label="报名号" width="120"></el-table-column>
        
        <el-table-column label="团信息" width="220">
          <template #default="{ row }">
            <div class="flex items-center">
              <div class="bg-primary-200 p-2 rounded mr-3">
                <i class="fa fa-suitcase text-primary-800"></i>
              </div>
              <div>
                <div class="font-medium text-gray-800">{{ row.groupTourName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="用户信息" width="160">
          <template #default="{ row }">
            <div>
              <div class="font-medium text-gray-800">{{ row.userName }}</div>
              <div class="text-xs text-gray-500">{{ row.userPhone }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="报名信息" width="180">
          <template #default="{ row }">
            <div>
              <div class="font-medium text-gray-800">￥{{ row.transactionAmount }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="行程信息" width="220">
          <template #default="{ row }">
            <div>
              <div class="flex items-center">
                <i class="fa fa-calendar-o text-gray-500 mr-1"></i>
                <span class="text-sm text-gray-800">
                  {{ formatDate(row.startDate) }} 至 {{ formatDate(row.endDate) }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="活动状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.progressStatus)">
              {{ row.progressStatus }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="handleView(row)" class="btn-primary">
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-area bg-white rounded-lg shadow mt-6 p-4 flex justify-center">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 详情对话框 -->
    <el-dialog v-model="dialogVisible" title="报名详情" width="50%">
      <div class="detail-dialog">
        <div class="detail-section">
          <h3 class="text-lg font-semibold text-gray-800 mb-3">基本信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div class="flex items-center">
              <span class="w-24 text-gray-500">报名号：</span>
              <span class="font-medium">{{ detail.registrationNumber }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">团名称：</span>
              <span class="font-medium">{{ detail.groupTourName }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">用户名：</span>
              <span class="font-medium">{{ detail.userName }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">联系电话：</span>
              <span class="font-medium">{{ detail.userPhone }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">报名费用：</span>
              <span class="font-medium">￥{{ detail.transactionAmount }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">报名时间：</span>
              <span class="font-medium">{{ formatDate(detail.registrationTime) }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">跟团游活动状态：</span>
              <el-tag :type="getStatusType(detail.progressStatus)">{{ detail.progressStatus }}</el-tag>
            </div>
          </div>
        </div>
        <div class="detail-section mt-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-3">行程信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div class="flex items-center">
              <span class="w-24 text-gray-500">出发日期：</span>
              <span class="font-medium">{{ formatDate(detail.startDate) }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">结束日期：</span>
              <span class="font-medium">{{ formatDate(detail.endDate) }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">行程天数：</span>
              <span class="font-medium">{{ detail.duration }}天{{ detail.duration - 1 }}晚</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-gray-500">集合地点：</span>
              <span class="font-medium">{{ detail.assemblyPlace }}</span>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="btn-secondary">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

export default {
  data() {
    return {
      searchForm: {
        groupName: '',
        userName: '',
        dateRange: []
      },
      tableData: [],
      selectedRows: [],
      loading: false,
      total: 0,
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      dialogVisible: false,
      detail: {},
      todayRegistrations: 0,
      popularToursCount: 0,
      travelAgencyId: null
    };
  },
  
  computed: {
    formattedTableData() {
      return this.tableData.map(item => ({
        ...item,
        duration: dayjs(item.endDate).diff(dayjs(item.startDate), 'day') + 1,
        registrationNumber: this.generateRegistrationNumber(item.registrationId)
      }));
    }
  },
  
  methods: {
    // 生成报名号（字母+4位数字）
    generateRegistrationNumber(id) {
      const prefix = String.fromCharCode(65 + Math.floor(Math.random() * 26)); // 随机字母A-Z
      const paddedId = id.toString().padStart(4, '0').slice(-4); // 4位数字
      return `${prefix}${paddedId}`;
    },

    // 加载旅行社信息
    async loadAgencyInfo() {
      try {
        const loginId = localStorage.getItem('loginId');
        if (!loginId) {
          this.$message.error('未获取到用户信息，请重新登录');
          this.$router.push('/loginpage');
          return;
        }

        // 调用后端API获取旅行社信息
        const response = await fetch(`http://localhost:8080/mw/travelAgency/byLoginId/${loginId}`);
        const data = await response.json();

        if (response.ok) {
          this.travelAgencyId = data.travelAgencyId;
          this.fetchData();
        } else {
          throw new Error(data.message || '获取旅行社信息失败');
        }
      } catch (error) {
        this.$message.error(error.message);
        console.error('加载旅行社信息失败:', error);
      }
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '-';
      return dayjs(timestamp).format('YYYY-MM-DD');
    },
    
    // 获取状态标签样式
    getStatusType(status) {
      if (!status) return 'info';
      switch(status) {
        case '未开始':
        case '未审核':
          return 'primary';
        case '报名中':
        case '进行中':
          return 'success';
        case '报名截止':
        case '已结束':
          return 'info';
        case '未通过':
          return 'danger';
        default:
          return 'info';
      }
    },
    
    // 计算统计信息
    calculateStats() {
      const today = dayjs().startOf('day');
      this.todayRegistrations = this.tableData.filter(item => 
        dayjs(item.registrationTime).isAfter(today)
      ).length;
      
      const tourCounts = {};
      this.tableData.forEach(item => {
        tourCounts[item.groupTourId] = (tourCounts[item.groupTourId] || 0) + 1;
      });
      this.popularToursCount = Object.values(tourCounts).filter(count => count >= 10).length;
    },
    
    // 获取数据
    async fetchData() {
      this.loading = true;
      try {
        if (!this.travelAgencyId) {
          throw new Error('旅行社ID不存在');
        }

        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          agencyId: this.travelAgencyId,
          keyword: this.searchForm.groupName || this.searchForm.userName
        };

        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = dayjs(this.searchForm.dateRange[0]).format('YYYY-MM-DD');
          params.endDate = dayjs(this.searchForm.dateRange[1]).format('YYYY-MM-DD');
        }

        const response = await axios.get('/gtr/agency/registrations', { params });
        
        this.tableData = response.data.list;
        this.total = response.data.total;
        this.calculateStats();
      } catch (error) {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败: ' + (error.response?.data?.message || error.message || '请重试'));
      } finally {
        this.loading = false;
      }
    },
    
    // 处理搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    
    // 处理重置
    handleReset() {
      this.searchForm = {
        groupName: '',
        userName: '',
        dateRange: []
      };
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    
    // 处理选择变化
    handleSelectionChange(rows) {
      this.selectedRows = rows.map(row => row.registrationId);
    },
    
    // 处理分页大小变化
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchData();
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.fetchData();
    },
    
    // 处理查看详情
    handleView(row) {
      this.detail = {
        ...row,
        registrationNumber: this.generateRegistrationNumber(row.registrationId),
        duration: dayjs(row.endDate).diff(dayjs(row.startDate), 'day') + 1
      };
      this.dialogVisible = true;
    }
  },
  
  mounted() {
    this.loadAgencyInfo();
  }
};
</script>

<style scoped>
.page-header {
  padding: 20px 0;
  background-color: #f9f9f9;
  border-bottom: 2px solid #eaeaea;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.stats {
  display: flex;
  gap: 16px;
  margin-top: 20px;
}

.stat-card {
  background-color: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  flex: 1;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.search-area {
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.table-area {
  overflow: hidden;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.pagination-area {
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

/* 动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.animate-pulse {
  animation: pulse 2s infinite;
}

/* 按钮样式 */
.btn-primary {
  background-color: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.btn-primary:hover {
  background-color: #45a049;
}

.btn-secondary {
  background-color: #f0f0f0;
  color: #333;
  border-color: #eaeaea;
}

.btn-secondary:hover {
  background-color: #e0e0e0;
}

/* 详情对话框样式 */
.detail-dialog {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.detail-section .grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.detail-section .grid div {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.detail-section .grid span {
  margin-right: 8px;
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>